<?php

namespace app\index\controller;

use think\Controller;
use app\index\model\Member;
use app\index\model\OrderProfit;
use app\index\model\Recharge;
use app\index\model\Getcash;
use app\index\model\Putlog;
use app\index\model\Order;
use app\index\model\Batchpay;
use app\firm\model\ProjectUser;
use app\firm\model\MoneyReturn;
use app\firm\model\MoneyReturns;
use app\firm\model\Project;
use app\firm\model\Notice;
use app\firm\model\MoneyCom;
use redis\Redis;
use expand\Yunst;

class Backcall extends Common {

    private $cModel;
    private $YunClass;
    public $param;
    private $puModel;
    private $mrsModel;

    public function _initialize() {
        parent::_initialize();
        $this->YunClass = new Yunst();
        $this->cModel = new Member();
        $this->puModel = new ProjectUser();
        $this->mrsModel = new MoneyReturns();
        $this->param = input('param.');
        //$this->param = unserialize(file_get_contents('BACK.txt'));	
        if (!$this->YunClass->CheckSign($this->param)) {
            file_put_contents('1.txt', serialize($this->param) . PHP_EOL, FILE_APPEND);
            return ajaxReturn('sign is error');
        }
        file_put_contents('130.txt', serialize($this->param) . PHP_EOL, FILE_APPEND);
    }

    //会员签约编号
    public function Qianyue() {
        $rps = $this->param['rps'];
        $rps = htmlspecialchars_decode($rps);
        $rps = json_decode($rps, true);
        if ($rps['status'] == 'OK') {
            $bizUserId = $rps['returnValue']['bizUserId'];
            $ContractNo = $rps['contractNo'];
            $this->cModel->where(['bizUserId' => $bizUserId])->update(['signContract' => $ContractNo]);
        }
    }

    //企业会员签约编号
    public function QyQianYue() {
        $rps = $this->param['rps'];
        $rps = htmlspecialchars_decode($rps);
        file_put_contents(date("Y-m-d H", time()) . 'qy_qianyue.txt', $rps . PHP_EOL, FILE_APPEND);
        $rps = json_decode($rps, true);
        if ($rps['status'] == 'OK') {
            $bizUserId = $rps['returnValue']['bizUserId'];
            $this->puModel->where(['bizUserId' => $bizUserId])->update(['is_sign' => 1]);
            $projectuser_info = $this->puModel->where(array('bizUserId' => $bizUserId))->find()->toArray();
            $redis = Redis::instance();
            $token = $redis->get('user:' . $projectuser_info['id']);
            $data['modify'] = true;
            $redis->hSet('firm_info', $token, json_encode($data));
            ajaxReturn('success', 1);
        }
    }


    //充值结果通知
    public function recharge() {
        $rps = $this->param['rps'];
        $rps = htmlspecialchars_decode($rps);
        $rps = json_decode($rps, true);

        $RecModel = new Recharge();
        $returnValue = $rps['returnValue'];

        $orderInfo = $RecModel->where(['order' => $returnValue['bizOrderNo'], 'orderNo' => $returnValue['orderNo']])->find();
        if (empty($orderInfo)) {
            return ajaxReturn('order is null');
        }

        if ($rps['status'] == 'error') {
            $RecModel->where(['id' => $orderInfo['id']])->update(['status' => 0]);
            return ajaxReturn('pay error');
        }
        if ($rps['status'] == 'OK') {
            if ($orderInfo['status'] == 2) {
                return ajaxReturn('double pay');
            }
            $RecModel->where(['id' => $orderInfo['id']])->update(['status' => 2]);
            $userId = $orderInfo['user_id'];
            $MemberInfo = $this->cModel->where(['id' => $userId])->find();
            if (empty($MemberInfo)) {
                return ajaxReturn('member is null');
            }
            $amount = $orderInfo['money']; //扣手续费
            $money = $MemberInfo['money'] + $amount;
            $res = $this->cModel->where(['id' => $userId])->update(['money' => $money]);
            if ($res) {
                $logModel = new Putlog();
                $log = [
                    'uid' => $userId,
                    'money' => $amount,
                    'type' => 2,
                    'order' => 'OD' . create_order(),
                    'status' => 1,
                    'crate_time' => time()
                ];
                $logModel->allowField(true)->save($log);
                TobeNotice2($userId, '充值通知', '充值金额￥' . $amount . '已到账');
                return ajaxReturn('success', 1);
            }
        }
    }

    /*
     * 企业充值回调
     * @author cpy(1442435897@qq.com)
     * @return \think\response\Json
     */

    public function rechargeReturn() {
        $rps = $this->param['rps'];
        $rps = htmlspecialchars_decode($rps);
        $rps = json_decode($rps, true);
        $returnValue = $rps['returnValue'];
        
        $moneyCom = new MoneyCom();
        $redis = Redis::instance();

        if ($rps['status'] == 'OK') {
            Db::startTrans();
            try {
                $where['order_num'] = ['eq', $returnValue['bizOrderNo']];
                $info = $moneyCom->getInfo($where);
                $row = $moneyCom->save(['status' => 3], ['order_num' => $returnValue['bizOrderNo']]);
                $res = $this->puModel->where('id', $info['company_id'])->setinc('money', $info['true_money']);
                if ($row && $res) {
                    Db::commit();
                    $token = $redis->get('user:' . $user_info['id']);
                    $user_info['money'] = $user_info['money'] + $info['true_money'];
                    $redis->hSet('firm_info', $token, json_encode($user_info));
                    $result = Config::get('code.success');
                    return ajaxReturn('success', 1);
                } else {
                    return ajaxReturn('error');
                }
            } catch (\Exception $e) {
                Db::rollback();
                return $e;
            }
        } else {
            $moneyCom->save(['status' => 4], ['order_num' => $returnValue['bizOrderNo']]);
        }
    }

    //提现回调
    public function getcash() {
        $rps = $this->param['rps'];
        $rps = htmlspecialchars_decode($rps);
        $rps = json_decode($rps, true);

        $cashModel = new Getcash();
        $returnValue = $rps['returnValue'];

        $orderInfo = $cashModel->where(['order' => $returnValue['bizOrderNo']])->find();
        if (empty($orderInfo)) {
            return ajaxReturn('order is null');
        }
        if ($orderInfo['status'] != 1) {
            return ajaxReturn('order is not status');
        }
        if ($rps['status'] == 'error') {
            $cashModel->where(['id' => $orderInfo['id']])->update(['status' => 3]);
            $res = $this->cModel->where(['id' => $orderInfo['user_id']])->setInc('money', $orderInfo['money']);
            if ($res) {
                $logModel = new Putlog();
                $log = [
                    'uid' => $orderInfo['user_id'],
                    'money' => $orderInfo['money'],
                    'type' => 3, //退还
                    'order' => 'OD' . create_order(),
                    'status' => 1,
                    'crate_time' => time()
                ];
                $logModel->allowField(true)->save($log);
                TobeNotice2($orderInfo['user_id'], '提现通知', $rps['message']);
            }
            return ajaxReturn('pay error');
        }
        if ($rps['status'] == 'OK') {
            $cashModel->where(['id' => $orderInfo['id']])->update(['status' => 2]);
            TobeNotice2($orderInfo['user_id'], '提现通知', '提现成功入账!');
            return ajaxReturn('success', 1);
        }
    }

    //消费回调
    public function consume() {
        
    }

    //代收回调
    public function apply() {
        $rps = $this->param['rps'];
        $rps = htmlspecialchars_decode($rps);
        file_put_contents('120.txt', $rps, FILE_APPEND);
        $rps = json_decode($rps, true);
        $orderModel = new Order();
        $returnValue = $rps['returnValue'];

        $orderInfo = $orderModel->where(['order_sn' => $returnValue['bizOrderNo']])->find();
        if (empty($orderInfo)) {
            return ajaxReturn('order is null');
        }
        /* if($orderInfo['status']==1){
          return ajaxReturn('pay again');
          } */
        if ($rps['status'] == 'OK') {
            //扣款
            $res = $this->cModel->where(['id' => $orderInfo['uid']])->setDec('money', $orderInfo['money']);
            if ($res) {
                //添加消费记录
                $putModel = new Putlog();
                $log = [
                    'order' => 'OD' . create_order(),
                    'uid' => $orderInfo['uid'],
                    'money' => -$orderInfo['money'],
                    'type' => 1,
                    'status' => 1,
                    'create_time' => time()
                ];
                $logid = $putModel->allowField(true)->save($log);
                //项目状态
                $orderModel->where(['id' => $orderInfo['id']])->update(['status' => 2]);
                $opModel = new OrderProfit();
                $mModel = new Member();
                $data = $opModel->where(['order_sn' => $returnValue['bizOrderNo']])->find();
                if ($data) {
                    $opModel->where(['order_sn' => $returnValue['bizOrderNo']])->update(['status' => 1]);
                    $money = $mModel->where(['id' => $data['member_id']])->value('money');
                    $new_money = $money + $data['money'];
                    $mModel->where(['id' => $data['member_id']])->update(['money' => $new_money]);
                    TobeNotice2($data['member_id'], '佣金通知', '下级支持项目,获得佣金' . $data['money'] . '元。');
                }

                return ajaxReturn('success', 1);
            }
        }
    }

    /*
     * 企业回款代收回调
     * @author cpy(1442435897@qq.com)
     * @return \think\response\Json
     */

    public function payBackReturn() {
        $rps = $this->param['rps'];
        $rps = htmlspecialchars_decode($rps);
        file_put_contents('qiyedaishou.txt', $rps, FILE_APPEND);
        $rps = json_decode($rps, true);
        $returnValue = $rps['returnValue'];

        $monReturn = new MoneyReturn();
        $monReturns = new MoneyReturns();
        $orderModel = new Order();
        $notice = new Notice();
        $project = new Project();

        $monReturnInfo = $monReturn->where(['order_on' => $returnValue['bizOrderNo']])->find();
        if (empty($monReturnInfo)) {
            return ajaxReturn('order is null');
        }

        if ($rps['status'] == 'OK') {
            Db::startTrans();
            try {
                $row = $monReturn->save(['status' => 2], ['id' => $monReturnInfo['id']]);
                $datas = [
                    'uid' => $user_info['id'],
                    'title' => '回款',
                    'content' => '您好,企业家,您于' . date('Y-m-d H:i:s') . '成功完成项目' . $proInfo['project_name'] . '的回款做操,回款金额' . $param['money'] . '元,如有疑问,欢迎致电400-605-9006',
                    'type' => 2
                ];
                $tag = $notice->save($datas);
                if ($row && $tag) {
                    Db::commit();
                    $pwhere['id'] = ['eq', $monReturnInfo['project_id']];
                    $pMoney = $project->getInfo($where, 'target_code');
                    $scale = sprintf("%.2f", $monReturnInfo['money'] / $pMoney['target_code']);
                    $where['project_id'] = ['eq', $monReturnInfo['project_id']];
                    $res = $orderModel->selectInfo($where, '*');
                    foreach ($res as $k => $v) {
                        $data = [
                            'order_id' => $v['id'],
                            'uid' => $v['uid'],
                            'project_id' => $v['project_id'],
                            'money_profit' => sprintf("%.2f", $v['money'] * $scale),
                        ];
                        $monReturns->save($data);
                    }
                } else {
                    return ajaxReturn('error');
                }
            } catch (\Exception $e) {
                Db::rollback();
                return $e;
            }
        } else {
            $this->puModel->where(['id' => $monReturnInfo['company_id']])->setInc('money', $monReturnInfo['money']);
        }
        return ajaxReturn('success', 1);
    }

    //代付回调
    public function signalpay() {
        $rps = $this->param['rps'];
        $rps = htmlspecialchars_decode($rps);
        $rps = json_decode($rps, true);
        //print_r($rps);
    }

    //批量代付回调
    public function batchpay() {
        $rps = $this->param['rps'];
        $rps = htmlspecialchars_decode($rps);
        $rps = json_decode($rps, true);

        if ($rps['status'] != 'OK') {
            return ajaxReturn('pay error');
        }

        $orderModel = new Order();
        $batchModel = new Batchpay();
        $returnValue = $rps['returnValue'];

        $orderInfo = $batchModel->where(['bizOrderNo' => $returnValue['bizOrderNo']])->find();
        if (empty($orderInfo)) {
            return ajaxReturn('order is null');
        }
        if ($orderInfo['orderNo']) {
            return ajaxReturn('pay again');
        }
        $amount = $returnValue['amount'] / 100;
        //改变项目订单状态
        $orderModel->where(['project_id' => $orderInfo['project_id'], 'uid' => $orderInfo['uid'], 'status' => 1])->update(['status' => 2]);
        $batchModel->where(['id' => $orderInfo['id']])->update(['orderNo' => $returnValue['orderNo'], 'payDate' => $returnValue['payDatetime']]);
        //返回金额
        $res = $this->cModel->where(['id' => $orderInfo['uid']])->setInc('money', $amount);
        if ($res) {
            $logModel = new Putlog();
            $log = [
                'uid' => $orderInfo['uid'],
                'money' => $amount,
                'type' => 3, //退还
                'order' => 'OD' . create_order(),
                'status' => 1,
                'crate_time' => time()
            ];
            $logModel->allowField(true)->save($log);
            TobeNotice2($orderInfo['uid'], '退还通知', '项目本金返还' . $amount . '元。');
        }
        return ajaxReturn('success', 1);
    }

    //退款回调
    public function backorder() {
        
    }

    /**
     * 项目方设置企业信息回调
     * @author hey_heyang(635870453@qq.com)
     */
    public function backproject() {
        $puModel = new ProjectUser();
        $rps = $this->param['rps'];
        $rps = htmlspecialchars_decode($rps);
        file_put_contents(date("Y-m-d H", time()) . 'verify_project.txt', $rps . PHP_EOL, FILE_APPEND);
        $rps = json_decode($rps, true);
        $returnValue = $rps['returnValue'];
        $bizUserId = $returnValue['bizUserId'];
        $projectuser_info = $puModel->where(array('bizUserId' => $bizUserId))->find()->toArray();
        if ($returnValue['result'] == 2) { //审核成功
            $puModel->where(array('bizUserId' => $bizUserId))->update(array('status' => 5, 'tonglian_msg' => $returnValue['remark'], 'tonglian_check_time' => strtotime($returnValue['checkTime'])));
            companyTobeNotice($projectuser_info['id'], '企业信息审核成功', '您的企业信息审核已通过');
        } elseif ($returnValue['result'] == 3) { //审核失败
            $puModel->where(array('bizUserId' => $bizUserId))->update(array('status' => 4, 'tonglian_msg' => $returnValue['failReason'], 'tonglian_check_time' => strtotime($returnValue['checkTime'])));
            companyTobeNotice($projectuser_info['id'], '企业信息审核失败', '您的企业信息审核失败，原因是:'. $returnValue['failReason']);
        }
        $redis = Redis::instance();
        $token = $redis->get('user:' . $projectuser_info['id']);
        $data['modify'] = true;
        $redis->hSet('firm_info', $token, json_encode($data));
        ajaxReturn('success', 1);
    }

    /**
     * 项目批量代付回调
     * @author hey_heyang(635870453@qq.com)
     */
    public function orderBatchPay() {
        $rps = $this->param['rps'];
        $rps = htmlspecialchars_decode($rps);
        file_put_contents(date("Y-m-d H", time()) . 'batch_order_list.txt', $rps . PHP_EOL, FILE_APPEND);
        $rps = json_decode($rps, true);
        if ($rps['status'] != 'OK') {
            ajaxReturn('pay error');
        }

        $orderModel = new Order();
        $batchModel = new Batchpay();
        $puModel = new ProjectUser();
        $returnValue = $rps['returnValue'];
        $amount = $returnValue['amount'] / 100;
        $orderInfo = $batchModel->where(['bizOrderNo' => $returnValue['bizOrderNo']])->find()->toArray();
        if (empty($orderInfo)) {
            ajaxReturn('order is null');
        }
        if ($orderInfo['orderNo']) {
            ajaxReturn('pay again');
        }
        //改变项目订单状态
        $orderModel->where(['project_id' => $orderInfo['project_id'], 'uid' => $orderInfo['uid'], 'status' => array('gt', 1), 'payment_status' => array('neq', 1)])->update(['payment_status' => 1]);
        $batchModel->where(['id' => $orderInfo['id']])->update(['orderNo' => $returnValue['orderNo'], 'payDate' => $returnValue['payDatetime']]);

        //项目方余额回写
        $pModel = new Project();
        $project_info = $pModel->where(['id'=>$orderInfo['project_id']])->find()->toArray();
        $puModel->where(['id'=>$project_info['initiator']])->setInc('money', $amount);
        $redis = Redis::instance();
        $token = $redis->get('user:' . $project_info['initiator']);
        $data['modify'] = true;
        $redis->hSet('firm_info', $token, json_encode($data));
        companyTobeNotice($project_info['initiator'], '投资金额入账', '项目投资金额' . $amount . '元。');

        ajaxReturn('success', 1);
    }

    /**
     * 项目批量兑付回调
     * @author hey_heyang(635870453@qq.com)
     */
    public function orderDuiFuiBatchPay() {
        $rps = $this->param['rps'];
        $rps = htmlspecialchars_decode($rps);
        file_put_contents(date("Y-m-d H", time()) . 'duifu_batch_order_list.txt', $rps . PHP_EOL, FILE_APPEND);
        $rps = json_decode($rps, true);
        if ($rps['status'] != 'OK') {
            ajaxReturn('pay error');
        }

        $orderModel = new Order();
        $batchModel = new Batchpay();
        $memberModel = new Member();
        $returnValue = $rps['returnValue'];
        $amount = $returnValue['amount'] / 100;

        $orderInfo = $batchModel->where(['bizOrderNo' => $returnValue['bizOrderNo']])->find()->toArray();
        if (empty($orderInfo)) {
            ajaxReturn('order is null');
        }
        if ($orderInfo['orderNo']) {
            ajaxReturn('pay again');
        }
        //改变关联订单状态
//        $orderModel->where(['project_id' => $orderInfo['project_id'], 'uid' => $orderInfo['uid'], 'status' => array('gt', 1), 'payment_status' => array('neq', 1)])->update(['status' => 3]);

        $this->mrsModel->where(['uid' => $orderInfo['uid'],'project_id'=>$orderInfo['orderInfo'],'status'=>1])->update(['status' => 2]);
        $batchModel->where(['id' => $orderInfo['id']])->update(['orderNo' => $returnValue['orderNo'], 'payDate' => $returnValue['payDatetime']]);
        $res = $memberModel->where(['id' => $orderInfo['uid']])->setInc('money', $amount);
        if ($res) {
            $logModel = new Putlog();
            $log = [
                'uid' => $orderInfo['uid'],
                'money' => $amount,
                'type' => 3, //退还
                'order' => 'OD' . create_order(),
                'status' => 1,
                'crate_time' => time()
            ];
            $logModel->allowField(true)->save($log);
            TobeNotice2($orderInfo['uid'], '退还通知', '项目本金返还' . $amount . '元。');
        }
        ajaxReturn('success', 1);
    }

    /**
     * 企业提现回调
     * @author hey_heyang(635870453@qq.com)
     */
    public function companyGetCash() {
        $rps = $this->param['rps'];
        $rps = htmlspecialchars_decode($rps);
        file_put_contents(date("Y-m-d H", time()) . 'company_get_cash.txt', $rps . PHP_EOL, FILE_APPEND);
        $rps = json_decode($rps, true);
        $cashModel = new MoneyCom();
        $returnValue = $rps['returnValue'];

        $orderInfo = $cashModel->where(['order_num' => $returnValue['bizOrderNo']])->find()->toArray();
        if (empty($orderInfo)) {
            ajaxReturn('order is null');
        }
        if ($orderInfo['status'] != 2) {
            ajaxReturn('order is not status');
        }
        if ($rps['status'] == 'error') {
            $cashModel->where(['id' => $orderInfo['id']])->update(['status' => 4]);
            $res = $this->puModel->where(['id' => $orderInfo['company_id']])->setInc('money', $orderInfo['money']);
            if ($res) {
                $logModel = new Putlog();
                $log = [
                    'uid' => $orderInfo['user_id'],
                    'money' => $orderInfo['money'],
                    'type' => 3, //退还
                    'order' => 'OD' . create_order(),
                    'status' => 1,
                    'crate_time' => time(),
                    'iscom' => 1,
                ];
                $logModel->allowField(true)->save($log);
                companyTobeNotice($orderInfo['company_id'], '提现通知', $rps['message']);
            }
            ajaxReturn('pay error');
        }
        if ($rps['status'] == 'OK') {
            $cashModel->where(['id' => $orderInfo['id']])->update(['status' => 3]);
            companyTobeNotice($orderInfo['company_id'], '提现通知', '提现成功入账!');
            ajaxReturn('success', 1);
        }
    }

}
